<template>
  <div class="chats-container relative">
    <div
      class="flex items-center sticky top-0 z-10 h-20 px-4 rounded-3xl rounded-b-none border-b bg-card backdrop-filter backdrop-blur-sm"
    >
      <img
        src="@/assets/customer.jpg"
        alt
        class="w-12 h-12 object-cover rounded-full"
      />
      <div class="ml-2 flex flex-col items-start">
        <span class="text-md font-semibold">智能客服-小干同学</span>
        <div>
          <el-icon class="text-green-600 align-middle"
            ><SuccessFilled
          /></el-icon>
          <span class="text-xs text-green-600 align-middle ml-1">24h在线</span>
        </div>
      </div>
    </div>
    <div
      id="chat-box"
      class="bg-card px-14 absolute bottom-0 top-0 left-0 right-0 overflow-y-auto pt-32 rounded-3xl shadow-md"
    >
      <div class="text-base flex flex-col gap-14 pb-32">
        <div v-for="(item, index) in info" :key="index">
          <div v-if="item.type === 'leftinfo'" class="relative">
            <span
              class="absolute left-0 -top-6 w-12 h-12 rounded-full bg-gray-200"
            >
              <img
                src="@/assets/customer.jpg"
                alt
                class="w-full h-full object-cover rounded-full"
              />
            </span>
            <div
              class="bg-leftinfo inline-block py-4 px-4 rounded-3xl ml-16 text-black dark:text-white mb-1 max-w-3xl"
            >
              <div>{{ item.content }}</div>
              <div
                v-for="(item2, index) in item.question"
                :key="index"
                class="text-blue-500 h-7 leading-7 cursor-pointer"
                @click="clickRobot(item2.content, item2.id)"
              >
                <div class="float-left">
                  {{ item2.index }} {{ item2.content }}
                </div>
              </div>
            </div>
            <div class="absolute left-16 text-gray-500 text-sm">
              {{ item.time }}
            </div>
          </div>
          <div
            v-if="item.type === 'rightinfo'"
            class="text-right text-gray-800 relative"
          >
            <div
              class="inline-block py-4 px-4 bg-blue-600 rounded-xl rounded-tr-none mr-16 text-white mb-1 max-w-3xl"
            >
              <span>{{ item.content }}</span>
            </div>
            <span
              class="absolute right-0 -top-6 w-12 h-12 rounded-full bg-gray-200"
            >
              <img
                src="@/assets/touxiang.jpg"
                alt="用户头像"
                class="w-12 h-12 object-cover rounded-full"
              />
            </span>
            <div class="absolute right-16 text-gray-500 text-sm">
              {{ item.time }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="absolute z-20 bg-card bottom-0 left-0 right-0 flex items-center justify-between p-4 rounded-3xl"
    >
      <div class="w-full pr-4">
        <textarea
          rows="1"
          placeholder="请输入您的问题..."
          class="w-full bg-card px-4 py-3 h-12 text-gray-800 focus:outline-none focus:shadow-outline resize-none align-middle rounded-xl"
          id="text"
          v-model="customerText"
          @keyup.enter="sentMsg()"
        ></textarea>
      </div>
      <el-button
        @click="sentMsg()"
        class="px-8 h-12 m-0 rounded-xl bg-blue-500"
        type="primary"
      >
        <span class="align-middle">发送</span>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import { SuccessFilled } from "@element-plus/icons-vue";

function getTodayTime() {
  const day = new Date();
  let seconds = day.getSeconds();
  seconds = seconds < 10 ? "0" + seconds : seconds;
  let minutes = day.getMinutes();
  minutes = minutes < 10 ? "0" + minutes : minutes;
  return (
    day.getFullYear() +
    "-" +
    (day.getMonth() + 1) +
    "-" +
    day.getDate() +
    " " +
    day.getHours() +
    ":" +
    minutes +
    ":" +
    seconds
  );
}

const scrollToBottom = () => {
  document.getElementById("chat-box").scrollTo({
    top: document.body.scrollHeight,
    behavior: "smooth",
  });
};

const customerText = ref("");
const info = reactive([
  {
    type: "leftinfo",
    time: getTodayTime(),
    name: "robot",
    content: "您好，欢迎使用!",
    question: [
      { id: 1, content: "在哪里查询报到的时间和地点", index: 1 },
      { id: 2, content: "报到所需材料", index: 2 },
      { id: 3, content: "如何缴纳学费？", index: 3 },
      { id: 4, content: "关于新生体检", index: 4 },
      { id: 5, content: "如何进行学籍注册？", index: 5 },
    ],
  },
]);
let timer = null;
const robotQuestion = [
  { id: 1, content: "在哪里查询报到的时间和地点", index: 1 },
  { id: 2, content: "报到所需材料", index: 2 },
  { id: 3, content: "如何缴纳学费？", index: 3 },
  { id: 4, content: "关于新生体检", index: 4 },
  { id: 5, content: "如何进行学籍注册？", index: 5 },
];
const robotAnswer = [
  {
    id: 1,
    content:
      "请仔细阅读学校发送的录取通知书或相关通知，通常上面会详细说明报到的时间和地点。如果有疑问，可以联系学校招生办公室或查看学校官网的相关信息。",
    index: 1,
  },
  {
    id: 2,
    content:
      "一般来说，报到时需要携带以下材料：(1)录取通知书 (2)身份证及复印件 (3)高中毕业证书及复印件 (4)照片(一般是1寸或2寸) (5)体检报告学费和其他费用的缴费凭证。具体要求请参考学校的通知。",
    index: 2,
  },
  {
    id: 3,
    content:
      "学校通常会提供多种缴费方式，如银行转账、网上支付或现场缴费。请根据学校的指引选择合适的方式，并保留好缴费凭证。",
    index: 3,
  },
  {
    id: 4,
    content:
      "学校通常会安排统一的体检时间和地点。请携带好体检表和身份证，按时参加体检。如果需要提前体检，请按照学校的要求到指定医院进行体检，并将体检报告带到报到现场。",
    index: 4,
  },
  {
    id: 5,
    content:
      "报到当天，学校会安排新生进行学籍注册。请携带好相关材料，按照学校的指引完成注册手续。",
    index: 5,
  },
];

const sentMsg = () => {
  clearTimeout(timer);
  showTimer();
  let text = customerText.value.trim();
  if (text !== "") {
    const obj = {
      type: "rightinfo",
      time: getTodayTime(),
      content: text,
    };
    info.push(obj);
    appendRobotMsg(customerText.value);
    customerText.value = "";
    nextTick(() => {
      const contentHeight = document.getElementById("content");
      contentHeight.scrollTop = contentHeight.scrollHeight;
    });
  }
};

const appendRobotMsg = (text) => {
  clearTimeout(timer);
  showTimer();
  text = text.trim();
  let answerText = "";
  let flag = false;
  for (let i = 0; i < robotAnswer.length; i++) {
    if (robotAnswer[i].content.indexOf(text) !== -1) {
      flag = true;
      answerText = robotAnswer[i].content;
      break;
    }
  }
  if (flag) {
    const obj = {
      type: "leftinfo",
      time: getTodayTime(),
      name: "robot",
      content: answerText,
      question: [],
    };
    info.push(obj);
  } else {
    answerText = "您可能想问：";
    const obj = {
      type: "leftinfo",
      time: getTodayTime(),
      name: "robot",
      content: answerText,
      question: robotQuestion,
    };
    info.push(obj);
  }
  nextTick(() => {
    scrollToBottom();
  });
};

const sentMsgById = (val, id) => {
  clearTimeout(timer);
  showTimer();
  const robotById = robotAnswer.filter((item) => item.id === id);
  const obj_l = {
    type: "leftinfo",
    time: getTodayTime(),
    name: "robot",
    content: robotById[0].content,
    question: [],
  };
  const obj_r = {
    type: "rightinfo",
    time: getTodayTime(),
    name: "robot",
    content: val,
    question: [],
  };
  info.push(obj_r);
  info.push(obj_l);
  nextTick(() => {
    scrollToBottom();
  });
};

const clickRobot = (val, id) => {
  sentMsgById(val, id);
};

const endMsg = () => {
  const happyEnding = {
    type: "leftinfo",
    time: getTodayTime(),
    content: "退出",
    question: [],
  };
  info.push(happyEnding);
  nextTick(() => {
    scrollToBottom();
  });
};

const showTimer = () => {
  timer = setTimeout(endMsg, 1000 * 60);
};

onMounted(() => {
  showTimer();
});
</script>

<style>
.chats-container {
  height: calc(100vh - 9rem);
}
.bg-leftinfo {
  background-color: #f3f4f6;
}
html.dark .bg-leftinfo {
  background-color: #1d2331;
}
</style>
